package com.liusand.interceptor;

import com.alibaba.fastjson.JSON;
import com.liusand.common.UserThreadLocalUtils;
import com.liusand.exception.TokenException;
import com.liusand.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author :liusha
 * packageName :com.liusand.interceptor
 * fileName :TokenInterceptor
 * creationTime :2022/11/30 21:15
 */

public class TokenInterceptor implements HandlerInterceptor {

    private RedisTemplate redisTemplate;

    public TokenInterceptor(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("AuthorizationUser");
        if(!StringUtils.hasText(token)){
            throw new TokenException("token传入失败");
        }
        String userStr = (String) redisTemplate.opsForValue().get("token_" + token);
        if(userStr == null){
            throw new TokenException("token失效");
        }
        User user = JSON.parseObject(userStr, User.class);
        if(user == null){
            throw new TokenException("token失效");
        }
        UserThreadLocalUtils.setThreadLocal(user);
        redisTemplate.opsForValue().set("token_"+token, userStr, 30, TimeUnit.MINUTES);
        return true;
    }
}
